/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/5/22.
//

#include "sql/stmt/insert_stmt.h"
#include "common/log/log.h"
#include "storage/common/db.h"
#include "storage/common/table.h"
#include "util/date.h"
#include <stdlib.h>
#include <string>

InsertStmt::InsertStmt(Table *table, const Value *values, int value_amount)
  : table_ (table), values_(values), value_amount_(value_amount)
{}

RC InsertStmt::create(Db *db, const Inserts &inserts, std::vector<Stmt *>& stmts)
{
  const char *table_name = inserts.relation_name;
  if (nullptr == db || nullptr == table_name || inserts.value_num <= 0) {
    LOG_WARN("invalid argument. db=%p, table_name=%p, value_num=%d", 
             db, table_name, inserts.value_num);
    printf("invalid argument. db=%p, table_name=%p, value_num=%d\n", 
             db, table_name, inserts.value_num);
    return RC::INVALID_ARGUMENT;
  }

  // check whether the table exists
  Table *table = db->find_table(table_name);
  if (nullptr == table) {
    LOG_WARN("no such table. db=%s, table_name=%s", db->name(), table_name);
    printf("no such table. db=%s, table_name=%s\n", db->name(), table_name);
    return RC::SCHEMA_TABLE_NOT_EXIST;
  }

  // check the fields number
  // const Value *values = inserts.values;
  const int value_num = inserts.value_num;
  Value values[value_num];
  for (int i=0; i<value_num; i++) {
    values[i] = inserts.values[i];
    std::cout << *(int*)values[i].data << std::endl;
  }

  const TableMeta &table_meta = table->table_meta();
  const int field_num = table_meta.field_num() - table_meta.sys_field_num();

  if (value_num % field_num != 0 || value_num == 0) {
    LOG_WARN("schema mismatch. value num=%d, field num in schema=%d", value_num, field_num);
    printf("schema mismatch. value num=%d, field num in schema=%d\n", value_num, field_num);
    return RC::SCHEMA_FIELD_MISSING;
  }

  // if (field_num != value_num) {
  //   LOG_WARN("schema mismatch. value num=%d, field num in schema=%d", value_num, field_num);
  //   printf("schema mismatch. value num=%d, field num in schema=%d\n", value_num, field_num);
  //   return RC::SCHEMA_FIELD_MISSING;
  // }

  // check fields type
  const int sys_field_num = table_meta.sys_field_num();
  for (int i = 0; i < value_num; i++) {
    const FieldMeta *field_meta = table_meta.field(i%field_num + sys_field_num); //TODO
    const AttrType field_type = field_meta->type();
    const AttrType value_type = values[i].type;

    //TEXTS == CHARS
    if (field_type==TEXTS && value_type==CHARS) {
      printf("field_type==TEXTS && value_type==CHARS\n");
      continue;
    }

    /*---------------------------------------------------------------------------------*/
    // typecast: convert the value type to field type
    // Value value = inserts.values[i];
    if (field_type==FLOATS && value_type==INTS) {
      values[i].type = FLOATS;
      int tmp = *(int *)(values[i].data);
      float v = float(tmp);
      values[i].data = malloc(sizeof(v));
      memcpy(values[i].data, &v, sizeof(v));
      continue;

    } else if (field_type==INTS && value_type==FLOATS) {
      values[i].type = INTS;
      float tmp = *(float *)(values[i].data);
      int v = int(tmp+0.5);
      values[i].data = malloc(sizeof(v));
      memcpy(values[i].data, &v, sizeof(v));
      continue;

    } else if (field_type==CHARS && value_type==INTS) {
      values[i].type = CHARS;
      int tmp = *(int *)(values[i].data);
      std::string str = std::to_string(tmp);
      const char *v = str.c_str();
      values[i].data = strdup(v);
      continue;

    } else if (field_type==INTS && value_type==CHARS) {
      values[i].type = INTS;
      char* tmp = (char *)(values[i].data);
      std::string str(tmp);
      float tmp_v = atof(str.c_str());
      int v = int(tmp_v+0.5);
      values[i].data = malloc(sizeof(v));
      memcpy(values[i].data, &v, sizeof(v));
      continue;

    } else if (field_type==CHARS && value_type==FLOATS) { // 11.05 -> info char 由于char只有四个字节，截断为11.0，有没有精度问题？即是否应该为11.1?
      values[i].type = CHARS;
      float tmp = *(float *)(values[i].data);
      std::string str = std::to_string(tmp);
      while (str[str.size()-1] == '.' || str[str.size()-1] == '0') {
        //去掉末尾的.字符
        //去掉末尾的０字符
        if (str[str.size()-1] == '.') {
          str.erase(str.end()-1,str.end());
          break;
        }
        else {
          str.erase(str.end()-1,str.end());
        }
      }

      const char *v = str.c_str();
      values[i].data = strdup(v);
      continue;

    } else if (field_type==FLOATS && value_type==CHARS) {
      values[i].type = FLOATS;
      char* tmp = (char *)(values[i].data);
      std::string str(tmp);
      float v = atof(str.c_str());
      printf("%f\n",v);
      values[i].data = malloc(sizeof(v));
      memcpy(values[i].data, &v, sizeof(v));
      continue;
    }
  /*---------------------------------------------------------------------------------*/

    if (field_type != value_type) { // TODO try to convert the value type to field type
      LOG_WARN("field type mismatch. table=%s, field=%s, field type=%d, value_type=%d", 
               table_name, field_meta->name(), field_type, value_type);
      printf("field type mismatch. table=%s, field=%s, field type=%d, value_type=%d\n", 
               table_name, field_meta->name(), field_type, value_type);
      return RC::SCHEMA_FIELD_TYPE_MISMATCH;
    }

    if (field_type == DATES) {
      Value value = values[i];
      int date = *(int *)(value.data);
      if (!check_date(date)) {
        LOG_WARN("field date is of wrong format. table=%s, field=%s", table_name, field_meta->name());
        return RC::INVALID_ARGUMENT;
      }
    }
  }
  
  // everything alright
  int j = 0;
  int len = value_num / field_num;
  Value v[len][field_num];
  Stmt* stmt[len];

  for (int i=0; i<len; i++) {
    for(int k=0; k<field_num; k++) {
      v[j][k].type = values[i*field_num+k].type;
      v[j][k].data = values[i*field_num+k].data;
    }
    // std::cout << *(int *)(v[j][0].data) << std::endl;
    stmt[j] = new InsertStmt(table, v[j], field_num);
    stmts.push_back(stmt[j]);
    j++;
  }


  return RC::SUCCESS;
}
